package org.linlinjava.litemall.wx.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.storage.StorageService;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.wx.dto.UserInfo;
import org.linlinjava.litemall.wx.service.UserTokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

import static org.linlinjava.litemall.wx.util.WxResponseCode.AUTH_INVALID_ACCOUNT;

/**
 * 鉴权服务
 */
@RestController
@RequestMapping("/wx/auth")
@Validated
public class WxAuthAdminController {
    private final Log logger = LogFactory.getLog(WxAuthAdminController.class);

    @Autowired
    private LitemallUserAdminService userAdminService;

    @Autowired
    private LitemallTypeService typeService;

    @Autowired
    private LitemallImgService imgService;

    @Autowired
    private LitemallQuanService quanService;

    @Autowired
    private LitemallUserErService userErService;

    @Autowired
    private StorageService storageService;
    @Autowired
    private LitemallStorageService litemallStorageService;

    /**
     * 账号登录
     *
     * @param body    请求内容，{ username: xxx, password: xxx }
     * @param request 请求对象
     * @return 登录结果
     */
    @PostMapping("loginAdmin")
    public Object login(@RequestBody String body, HttpServletRequest request) {
        String username = JacksonUtil.parseString(body, "username");
        String password = JacksonUtil.parseString(body, "password");
        if (username == null || password == null) {
            return ResponseUtil.badArgument();
        }
        List<LitemallUserAdmin> userAdminList = userAdminService.queryByUsernameAdmin(username);
        LitemallUserAdmin userAdmin = null;
        if (userAdminList.size() > 1) {
            return ResponseUtil.serious();
        } else if (userAdminList.size() == 0) {
            return ResponseUtil.fail(AUTH_INVALID_ACCOUNT, "账号不存在");
        } else {
            userAdmin = userAdminList.get(0);
        }
        if (password == userAdmin.getPassword()) {
            return ResponseUtil.fail(AUTH_INVALID_ACCOUNT, "账号密码不对");
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setNickName(username);
        String token = UserTokenManager.generateToken(userAdmin.getId());
        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("token", token);
        result.put("user", userAdmin);
        result.put("userInfo", userInfo);
        return ResponseUtil.ok(result);
    }

    @PostMapping("selectByType")
    public Object selectByType() {
        return ResponseUtil.ok(typeService.queryByType());
    }

    @PostMapping("queryByType")
    public Object queryByType() {
        return typeService.queryByType();
    }


    @PostMapping("createType")
    public Object createType(@RequestBody LitemallType litemallType) {
        String val="";
        Random random = new Random();
        for (int i = 0; i < 9; i++) {
            val += String.valueOf(random.nextInt(9));
        }
        litemallType.setPid(val);
        if (litemallType.getName() == null || litemallType.getPid() == null || litemallType.getUrl() == null) {
            return ResponseUtil.badArgument();
        }
        String pid = litemallType.getPid();
        if (typeService.selectType(pid) == null) {
            return typeService.create(litemallType);
        } else {
            return ResponseUtil.badArgument();
        }
    }

    @DeleteMapping("deleteType")
    public Object deleteType(@RequestBody LitemallType litemallType) {
        int i = typeService.deleteById(litemallType.getId());
        return ResponseUtil.ok();
    }

    @PostMapping("selectByImg")
    public Object selectByImg() {
        return ResponseUtil.ok(imgService.queryByType());
    }


    @PostMapping("queryByImg")
    public Object queryByImg() {
        return imgService.queryByType();
    }


    @PostMapping("createImg")
    public Object createImg(@RequestBody LitemallImg litemallImg) {
        return imgService.create(litemallImg);
    }

    @DeleteMapping("deleteImg")
    public Object deleteById(@RequestBody LitemallImg litemallImg) {
        int i = imgService.deleteById(litemallImg.getId());
        return ResponseUtil.ok();
    }


    @PostMapping("createQuan")
    public Object createQuan(@RequestBody LitemallQuan litemallQuan) {
        litemallQuan.setTopping(0);
        LitemallType litemallType = typeService.selectType(String.valueOf(litemallQuan.getPid()));
        litemallQuan.setImages(litemallType.getUrl());
        return quanService.create(litemallQuan);
    }

    @PostMapping("queryAllUser")
    public Object queryAllUser() {
        return userErService.queryAllUser();
    }


    @PostMapping("createUser")
    public Object createUser(@RequestBody LitemallUserEr litemallUserEr) {
        LitemallUserEr userEr=userErService.queryAllById(litemallUserEr.getUsername());
        if(null!=userEr){
            return ResponseUtil.fail(AUTH_INVALID_ACCOUNT,"该账号已存在！");
        }
        litemallUserEr.setDeleteId(0);
         int flag= (int) userErService.create(litemallUserEr);
        return ResponseUtil.ok();
    }

    /*   @PostMapping("createUsers")
    public int createUsers(@RequestBody List<LitemallUserEr> litemallUserErs){
        int users = userErService.createUsers(litemallUserErs);
        return users;
    }*/

    @PostMapping("createUsers")
    public Object createUser(@RequestBody String body, HttpServletRequest request) {
        int number = JacksonUtil.parseInteger(body, "number");
        String balance = JacksonUtil.parseString(body, "balance");
        LitemallUserEr litemallUserErs = new LitemallUserEr();
        for (int i = 0; i < number; i++) {
            String username = CreateFirstNum() + CreateUserName();
            String password = CreateFirstNum() + CreatePassword();
            litemallUserErs.setUsername(username);
            litemallUserErs.setPassword(password);
            litemallUserErs.setBalance(balance);
            litemallUserErs.setDeleteId(0);
            userErService.create(litemallUserErs);
        }
        return ResponseUtil.ok();
    }

    //生成随机数
    public String CreateUserName() {
        Random rand = new Random();
        String num = "";
        for (int a = 0; a < 7; a++) {
            //生成5位数字
            num += rand.nextInt(10);
        }
        return num;
    }

    public String CreatePassword() {
        Random rand = new Random();
        String num = "";
        for (int a = 0; a < 5; a++) {
            //生成3位数字
            num += rand.nextInt(10);
        }
        return num;
    }

    public String CreateFirstNum() {
        Random rand = new Random();
        String num = "";
        for (int a = 0; a < 1; a++) {
            //生成1位数字
            int i = rand.nextInt(9);
            return Integer.toString(i + 1);
        }
        return num;
    }

    public String returnUsername() {
        String username = CreateFirstNum() + CreateUserName();
        List<LitemallUserEr> userErs = userErService.queryByUsernameEr(username);
        if (userErs.size() != 0) {
            return returnUsername();
        } else {
            return username;
        }
    }

    public String returnPassword() {
        return CreateFirstNum() + CreatePassword();
    }


    @PostMapping("/createImage")
    public Object create(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        LitemallStorage litemallStorage = storageService.store(file.getInputStream(), file.getSize(),
                file.getContentType(), originalFilename);
        String url = litemallStorage.getUrl();
        return ResponseUtil.ok(litemallStorage);
    }
}
